using System.Linq;
using System.Web.Mvc;
using ExtendedMvc.Common.Diagnostics;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public class Button : ButtonBase<Button> {
		public Button(string caption, string name = null, string id = null) : base(HtmlButtonType.Button, caption, name, id) { }
	}

	public abstract class ButtonBase<T> : VisibleElement<T> where T : ButtonBase<T> {
		private bool _disabled;
		private string _name;

		private object _caption;

		protected ButtonBase(string type = HtmlButtonType.Button, string caption = null, string name = null, string id = null)
			: base(HtmlTag.Button, (id ?? name)) {
			Check.Argument.IsNotValid(type, "type", t => HtmlButtonType.Values.Contains(t));
			SetAttribute(HtmlAttribute.Type, type);
			Name(name);
			Caption(caption);
		}

		public virtual T Name(string value) {
			_name = HtmlAttribute.ClearInvalidChars(value);
			return (T)this;
		}

		public virtual T Caption(string value) {
			_caption = value;
			return (T)this;
		}

		public virtual T Disabled(bool value = true) {
			_disabled = value;
			return (T)this;
		}

		protected override TagRenderMode TagRenderMode { get { return TagRenderMode.Normal; } }

		protected override void Prepare() {
			if (!string.IsNullOrWhiteSpace(_name)) SetAttribute(HtmlAttribute.Name, _name);
			if (_disabled) {
				OnClick(null);
				SetAttribute(HtmlAttribute.Disabled, HtmlAttribute.Disabled);
			}
			base.Prepare();
		}

		protected override void SetContent() {
			Builder.InnerHtml = _caption.ToString();
		}
	}
}